# coding=utf-8
import hashlib,time,random,datetime
from common.models.Order import Order, OrderItem
from common.models.TableItem import TableItem
from sqlalchemy import extract, and_

class OrderLibs() :
    @staticmethod
    def geneOrderSn():
        m = hashlib.md5()
        sn = None
        while True:
            str = "%s-%s" % (int(round(time.time() * 1000)), random.randint(0, 9999999))
            m.update(str.encode("utf-8"))
            sn = m.hexdigest()
            if not Order.query.filter_by(order_sn=sn).first():
                break
        return sn

    @staticmethod
    def geneMealNumber(table_id):
        now = time.localtime(time.time())
        count = Order.query.filter(
            and_(
                extract('year', Order.created_time) == int(now.tm_year),
                extract('month', Order.created_time) == int(now.tm_mon)),
                extract('day', Order.created_time) == int(now.tm_mday) ).count()
        table_name = TableItem.query.filter_by(id=table_id).first().name
        return table_name + "-" + str(count+1)
